' 具体 下载 核心代码
'
' 下载完成会 打开 下载后的文件所在目录
'
' wscript.shell 处理文件目录名有空格 采用 chr(34)
'
dim url,file
objArgs = wscript.arguments(0)

' "参数1,参数2"   逗号之间不能有空格
' msgbox "objArgs=" & objArgs

objArgs = Trim(objArgs)
argsString = split(objArgs, ",")

' 长度是2，ubound返回是可用长度 从0开始  为1
argscount = ubound(argsString) + 1
' msgbox "argscount=" & argscount

if argscount < 2 then
  msgbox("invalid")
else
  url = argsString(0)
  file = argsString(1)
  ' msgbox "doing_down url=" & url & "    file=" & file
  GetHttpResult url, "UTF-8", file
end if

function GetHttpResult(url, charset, file)
  ' msgbox "GetHttpResult url=" & url
  ' msgbox "GetHttpResult charset=" & charset
  ' msgbox "GetHttpResult file=" & file
  dim http
  set http = CreateObject("Msxml2.ServerXMLHTTP")
  http.setTimeouts 10000, 10000, 10000, 30000 '设置超时时间
  http.Open "GET", url, False

  http.Send()

  ' msgbox "http.readystate=" &http.readystate
  if http.readystate = 4 then
    GetHttpResult = SaveToFile(http.ResponseBody, charset, file)
    ' msgbox "download-sucess " & file

    set objShell = CreateObject("Wscript.Shell")
    fileLeftIns = InStrRev(file, "/")
    if fileLeftIns < 1 then
      fileLeftIns = InStrRev(file, "\")
    end if
    ' msgbox "download-sucess " & file & "___" & fileLeftIns
    filePath = Left(file, fileLeftIns)
    ' msgbox "open filePath=" & filePath
    objShell.Run "explorer.exe /e," & filePath
  end if
end function

function SaveToFile(str, charset, file)
  dim objStream
  set objStream = CreateObject("Adodb.Stream")

  objStream.Type = 1
  objStream.Mode = 3
  objStream.Open()
  objStream.Write str
  objStream.Position = 0

  objStream.Type = 2
  objStream.charset = charset
  objStream.SaveToFile file,2
  objStream.Close()
  set objStream = Nothing
end function